package com.wenc.psi.rpstr;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.wenc.psi.dao.SaleDao;
import com.wenc.psi.dao.SaleDetailDao;
import com.wenc.psi.pojo.Sale;
import com.wenc.psi.pojo.SaleDetail;

import java.util.ArrayList;
import java.util.List;

public class SaleOrderRepository {
    private SaleDao saleDao;
    private SaleDetailDao saleDetailDao;
    private MutableLiveData<List<Sale>> saleLive;
    private List<Sale> saleList;

    public MutableLiveData<List<Sale>> getSaleLive() {
        return saleLive;
    }

    public List<Sale> getSaleList() {
        return saleList;
    }

    public SaleOrderRepository(Context context) {
        saleDao = new SaleDao();
        saleDetailDao = new SaleDetailDao();
        saleLive = new MutableLiveData<>();
        getAllSaleOrder();
    }

    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 200) {
                System.out.println("获取到数据");
                saleList = (List<Sale>) msg.obj;
                saleLive.setValue(saleList);
            }else if (msg.what == 400) {
                System.out.println("获取不到数据");
            }else if (msg.what == 250) {
                getAllSaleOrder();
            }
        }
    };

    public void getAllSaleOrder() {
        new Thread(() -> {
            Message message = new Message();
            List<Sale> sales = saleDao.getAllData();
            if (sales != null) {
                message.what = 200;
                message.obj = sales;
            } else {
                message.what = 400;
            }
            handler.sendMessage(message);
        }).start();
    }

    public void insertSale(Sale... sales){
        new Thread(() -> {
            saleDao.insert(sales);
        }).start();
    }

    public void insertSaleDetail(SaleDetail... saleDetails) {
        new Thread(() -> {
            saleDetailDao.insert(saleDetails);
        }).start();
    }
    // 插入销售单
    public void inserSaleOrder(Sale sale, SaleDetail... saleDetails){
        new Thread(() -> {
            Message message = new Message();
            saleDao.insertOrder(sale, saleDetails);
            message.what = 250;
            handler.sendMessage(message);
        }).start();
    }
}
